package com.oc.mba.res;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lurencun.android.support.widget.CommonAdapter;
import com.oc.mba.R;
import com.oc.mba.entity.OcPaper;

public class PaperAdapter extends CommonAdapter<OcPaper> {

	private Context mContext;

	final Handler handler;
	
	public PaperAdapter(Context context, Handler paperHandler) {
		super(context);
		mContext = context;
		handler = paperHandler;
	}

	protected View createView(LayoutInflater inflater, final OcPaper data,
			int position, View convertView, ViewGroup parent) {
		
		RelativeLayout cell = (RelativeLayout) inflater.inflate(R.layout.category_cell, null);
		TextView title = (TextView) cell.findViewById(R.id.paper_title);
		
		LinearLayout back_button = (LinearLayout) cell.findViewById(R.id.back_button);
		Button buyBtn = (Button) cell.findViewById(R.id.buyBtn);
		Button downBtn = (Button) cell.findViewById(R.id.downBtn);
		
		buyBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Message msg = Message.obtain(handler, 1, data.getId());
				handler.sendMessage(msg);
			}
		});
		
		downBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Message msg = Message.obtain(handler, 0, data);
				handler.sendMessage(msg);
			}
		});
		
		Double paperPrice = data.getPaperPrice();
		// 免费试题
		if (paperPrice == 0) {
			title.setText(data.getPaperTitle() + "(FREE)");
			back_button.setVisibility(View.VISIBLE);
			buyBtn.setVisibility(View.GONE);
			downBtn.setVisibility(View.VISIBLE);
		} 
		// 付费试题
		else {
			// 没有支付
			if (!data.isPaid()) {
				title.setText(data.getPaperTitle() + "(￥" + Double.toString(paperPrice) + ")");
				back_button.setVisibility(View.VISIBLE);
				buyBtn.setVisibility(View.VISIBLE);
				downBtn.setVisibility(View.GONE);
			}
			// 已经支付
			else {
				title.setText(data.getPaperTitle() + "(已支付)");
				back_button.setVisibility(View.VISIBLE);
				buyBtn.setVisibility(View.GONE);
				downBtn.setVisibility(View.VISIBLE);
			}
		}
		return cell;
	}
}
